package com.atguigu.yyj.config;

import com.atguigu.yyj.aspect.CacheAspect;
import com.atguigu.yyj.constant.CacheAbleConstant;
import com.atguigu.yyj.service.Impl.CacheOpsServiceImpl;
import org.redisson.Redisson;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * @Author：yyj
 * @Package：com.atguigu.tingshu.search.config
 * @Project：tingshu_parent240829
 * @name：RedissonConfig
 * @Date：2025/2/7 21:29
 * @Filename：RedissonConfig
 */
@Configuration
@Import(CacheOpsServiceImpl.class)
public class CacheAbleAutoConfiguration {
    @Autowired
    private RedisProperties redisProperties;
    @Autowired
    private StringRedisTemplate redisTemplate;


    /**
     * 定义Redisson的客户端
     *
     * @return
     */
    @Bean
    public RedissonClient redissonClient() {
        Config config = new Config();
        config.useSingleServer().setAddress(CacheAbleConstant.REDIS_CACHE_PROTOCOL + redisProperties.getHost() + CacheAbleConstant.REDIS_CACHE_PROTOCOL_SPLIT + redisProperties.getPort()).setPassword(redisProperties.getPassword());
        RedissonClient redissonClient = Redisson.create(config);
        return redissonClient;
    }


    /**
     * 定义分布式布隆过滤器
     */
    @Bean
    public RBloomFilter rbloomFilter(RedissonClient redissonClient){
        //1.获取布隆过滤器会创建一个新的,后面可以直接用的
//        redisTemplate.opsForValue().setIfAbsent(CacheA)
        // 主要保证幂等性（只有第一次才能完成布隆的初始化，后面服务不管重启多少次 都不会继续初始化）
        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(CacheAbleConstant.DISTRO_BLOOM_LOCK_KEY, CacheAbleConstant.DISTRO_BLOOM_LOCK_FLAG);
        RBloomFilter<Object> bloomFilter = redissonClient.getBloomFilter(CacheAbleConstant.DISTRO_BLOOM_NAME);
        if (aBoolean){
            // 2.初始化布隆过滤器
            bloomFilter.tryInit(CacheAbleConstant.DISTRO_BLOOM_SIZE, CacheAbleConstant.DISTRO_BLOOM_FPP);
            return bloomFilter;
        }
        //3.返回对象
        return bloomFilter;
    }

    /**
     * 定义一个切面
     */
    @Bean
    public CacheAspect cacheAspect() {

        return new CacheAspect();
    }

}